package org.example.adminbackend.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.adminbackend.client.AdCategoryServiceClient;
import org.example.adminbackend.client.AdServiceClient;
import org.example.adminbackend.common.Result;
import org.example.pojo.Ad;
import org.example.pojo.AdCategory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * Web页面控制器 - Admin Backend
 */
@Slf4j
@Controller
@RequestMapping("/web")
@RequiredArgsConstructor
public class WebController {

    private final AdServiceClient adServiceClient;
    private final AdCategoryServiceClient adCategoryServiceClient;

    /**
     * 广告列表页面
     */
    @GetMapping("/ads")
    public String adList(Model model) {
        try {
            // 获取广告列表
            Result<List<Ad>> adResult = adServiceClient.getAllAds();
            if (adResult.isSuccess()) {
                model.addAttribute("ads", adResult.getData());
            } else {
                model.addAttribute("error", "获取广告列表失败：" + adResult.getMessage());
            }
            
            // 获取分类列表用于显示分类名称
            Result<List<AdCategory>> categoryResult = adCategoryServiceClient.getAllCategories();
            if (categoryResult.isSuccess()) {
                model.addAttribute("categories", categoryResult.getData());
            } else {
                log.warn("获取分类列表失败：" + categoryResult.getMessage());
                // 分类获取失败不影响广告列表显示，只是不显示分类名称
            }
        } catch (Exception e) {
            log.error("获取广告列表失败", e);
            model.addAttribute("error", "获取广告列表失败：" + e.getMessage());
        }
        return "ad-list";
    }

    /**
     * 显示添加广告页面
     */
    @GetMapping("/ads/add")
    public String showAddAdForm(Model model) {
        try {
            // 获取分类列表
            Result<List<AdCategory>> result = adCategoryServiceClient.getAllCategories();
            if (result.isSuccess()) {
                model.addAttribute("categories", result.getData());
            } else {
                model.addAttribute("error", "获取分类列表失败：" + result.getMessage());
            }
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            model.addAttribute("error", "获取分类列表失败：" + e.getMessage());
        }
        return "ad-add";
    }

    /**
     * 处理添加广告请求
     */
    @PostMapping("/ads/add")
    public String addAd(@ModelAttribute Ad ad, RedirectAttributes redirectAttributes) {
        try {
            // 创建广告（图片URL由前端上传后设置）
            Result<Ad> result = adServiceClient.createAd(ad);
            if (result.isSuccess()) {
                redirectAttributes.addFlashAttribute("message", "广告添加成功！");
                return "redirect:/web/ads";
            } else {
                redirectAttributes.addFlashAttribute("error", "添加广告失败：" + result.getMessage());
                return "redirect:/web/ads/add";
            }
        } catch (Exception e) {
            log.error("添加广告失败", e);
            redirectAttributes.addFlashAttribute("error", "添加广告失败：" + e.getMessage());
            return "redirect:/web/ads/add";
        }
    }

    /**
     * 显示编辑广告页面
     */
    @GetMapping("/ads/edit/{id}")
    public String showEditAdForm(@PathVariable Integer id, Model model) {
        try {
            // 获取广告详情
            Result<Ad> adResult = adServiceClient.getAdById(id);
            if (!adResult.isSuccess()) {
                model.addAttribute("error", "获取广告详情失败：" + adResult.getMessage());
                return "redirect:/web/ads";
            }

            // 获取分类列表
            Result<List<AdCategory>> categoryResult = adCategoryServiceClient.getAllCategories();
            if (!categoryResult.isSuccess()) {
                model.addAttribute("error", "获取分类列表失败：" + categoryResult.getMessage());
                return "redirect:/web/ads";
            }

            model.addAttribute("ad", adResult.getData());
            model.addAttribute("categories", categoryResult.getData());
        } catch (Exception e) {
            log.error("获取编辑页面数据失败", e);
            model.addAttribute("error", "获取编辑页面数据失败：" + e.getMessage());
            return "redirect:/web/ads";
        }
        return "ad-edit";
    }

    /**
     * 处理编辑广告请求
     */
    @PostMapping("/ads/edit/{id}")
    public String editAd(@PathVariable Integer id,
                         @ModelAttribute Ad ad,
                         RedirectAttributes redirectAttributes) {
        try {
            // 更新广告（图片URL由前端上传后设置）
            ad.setId(id);
            Result<Ad> result = adServiceClient.updateAd(id, ad);
            if (result.isSuccess()) {
                redirectAttributes.addFlashAttribute("message", "广告更新成功！");
                return "redirect:/web/ads";
            } else {
                redirectAttributes.addFlashAttribute("error", "更新广告失败：" + result.getMessage());
                return "redirect:/web/ads/edit/" + id;
            }
        } catch (Exception e) {
            log.error("更新广告失败", e);
            redirectAttributes.addFlashAttribute("error", "更新广告失败：" + e.getMessage());
            return "redirect:/web/ads/edit/" + id;
        }
    }

    /**
     * 删除广告
     */
    @PostMapping("/ads/delete/{id}")
    @ResponseBody
    public String deleteAd(@PathVariable Integer id) {
        try {
            Result<String> result = adServiceClient.deleteAd(id);
            if (result.isSuccess()) {
                return "success";
            } else {
                return "error: " + result.getMessage();
            }
        } catch (Exception e) {
            log.error("删除广告失败", e);
            return "error: " + e.getMessage();
        }
    }

    /**
     * 分类管理页面（简单实现）
     */
    @GetMapping("/categories")
    public String categoryList(Model model) {
        try {
            Result<List<AdCategory>> result = adCategoryServiceClient.getAllCategories();
            if (result.isSuccess()) {
                model.addAttribute("categories", result.getData());
            } else {
                model.addAttribute("error", "获取分类列表失败：" + result.getMessage());
            }
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            model.addAttribute("error", "获取分类列表失败：" + e.getMessage());
        }
        return "category-list";
    }

    /**
     * 创建分类API
     */
    @PostMapping("/api/categories")
    @ResponseBody
    public Result<AdCategory> createCategory(@RequestBody AdCategory category) {
        try {
            return adCategoryServiceClient.createCategory(category);
        } catch (Exception e) {
            log.error("创建分类失败", e);
            return Result.error("创建分类失败：" + e.getMessage());
        }
    }

    /**
     * 更新分类API
     */
    @PutMapping("/api/categories/{id}")
    @ResponseBody
    public Result<AdCategory> updateCategory(@PathVariable Integer id, @RequestBody AdCategory category) {
        try {
            return adCategoryServiceClient.updateCategory(id, category);
        } catch (Exception e) {
            log.error("更新分类失败", e);
            return Result.error("更新分类失败：" + e.getMessage());
        }
    }

    /**
     * 删除分类API
     */
    @DeleteMapping("/api/categories/{id}")
    @ResponseBody
    public Result<String> deleteCategory(@PathVariable Integer id) {
        try {
            return adCategoryServiceClient.deleteCategory(id);
        } catch (Exception e) {
            log.error("删除分类失败", e);
            return Result.error("删除分类失败：" + e.getMessage());
        }
    }

    /**
     * 首页重定向到广告列表
     */
    @GetMapping("/")
    public String index() {
        return "redirect:/web/ads";
    }
}